//
//  PlacardViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/11/24.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "PlacardViewController.h"

#import "PlacardCell.h"

#import "MainManager.h"

@interface PlacardViewController ()

@property (nonatomic, strong) NoDataView *noNetWorkView;
@property (nonatomic, strong) NoDataView *noDataView;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, assign) NSInteger page;

@end

@implementation PlacardViewController

#pragma mark - VC Life

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.page = 1;
    
    self.view.backgroundColor = UIColorFromRGB(0xf1f1f1);
    self.navigationItem.title = kLocalizedString(@"公告详情", nil);
    
    [self initSubViews];
    
    if (self.isOneCell == NO) {
        [self.tableView.mj_header beginRefreshing];
    }
}

- (void)initSubViews
{
    self.tableView.tableFooterView = [UIView new];
    
    if (@available(iOS 11.0, *)){
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.estimatedRowHeight           = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.backgroundColor = UIColorFromRGB(0xf1f1f1);
    
    self.tableView.contentInset = UIEdgeInsetsMake(-7, 0, 0, 0);
    [self.tableView registerClass:[NoDateCell class] forCellReuseIdentifier:@"NoDataCellID"];
    
    if (!self.isOneCell) {
        __weak PlacardViewController *weakSelf = self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
             [weakSelf headerRefresh];
        }];
        
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
             [weakSelf footerRefresh];
        }];
    }
}

#pragma mark - RefreshAction

- (void)headerRefresh
{
    @weak(self)
    self.page = 1;
    [MainManager mainGetNewsListWithType:@"2" page:self.page block:^(NSDictionary *dic, HttpRequestResult result, NSString *msg) {
        [self_weak_ stopLoading];
        [self_weak_.tableView.mj_header endRefreshing];
        if (result == kHttpRequestResultNormal) {
            [self_weak_.noNetWorkView removeFromSuperview];
            self_weak_.dataArray = [NSMutableArray array];
            [self_weak_.dataArray addObjectsFromArray:dic[@"array"]];
            if (self_weak_.dataArray.count > 0) {
                self_weak_.page = self_weak_.page + 1;
                self_weak_.tableView.mj_footer.hidden = NO;
            }
            else {
                [self_weak_.noNetWorkView removeFromSuperview];
                self_weak_.tableView.mj_footer.hidden = YES;
                [self_weak_.tableView addSubview:self_weak_.noDataView];
            }
            
            if (self_weak_.page > [dic[@"totalPage"]intValue] ) {
                [self_weak_.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self_weak_.tableView.mj_footer endRefreshing];
            }
        }
        else {
            [HFStatusView showFailureMessage:kLocalizedString(@"网络异常，请稍后重试", nil)];
            if (self_weak_.dataArray.count == 0) {
                [self_weak_.noDataView removeFromSuperview];
                [self_weak_.view addSubview:self_weak_.noNetWorkView];
            }
        }
        [self_weak_.tableView reloadData];
    }];
}

- (void)footerRefresh
{
    @weak(self)
    [MainManager mainGetNewsListWithType:@"2" page:1 block:^(NSDictionary *dic, HttpRequestResult result, NSString *msg) {
        
        [self_weak_ stopLoading];
        
        if (result == kHttpRequestResultNormal) {
        
            [self_weak_.dataArray addObjectsFromArray:dic[@"array"]];
            
            if (((NSArray *)dic[@"array"]).count > 0) {
                self_weak_.page = self_weak_.page + 1;
            }
            if (self_weak_.page > [dic[@"totalPage"]intValue] ) {
                [self_weak_.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                 [self_weak_.tableView.mj_footer endRefreshing];
            }
        }
        else {
            [HFStatusView showFailureMessage:kLocalizedString(@"网络异常，请稍后重试", nil)];
            [self_weak_.tableView.mj_footer endRefreshing];
        }
        [self_weak_.tableView reloadData];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  self.isOneCell == YES ? 1 : self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PlacardCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    cell.backgroundColor = UIColorFromRGB(0xf1f1f1);
    cell.indexRow = indexPath.row;
    
    cell.model = self.isOneCell == YES ? self.oneCellModel : self.dataArray[indexPath.row];
    
    __weak PlacardViewController *weakSelf = self;
    [cell setPlacardCellBlock:^(NSInteger indexRow,BOOL isOpen) {
        MainNewsItemModel * model = [weakSelf.dataArray objectAtIndex:indexRow];
        
        model.isOpen = !isOpen;
        
        CGFloat titleHeigh = ceilf([NSString sizeWithString:model.title font:[UIFont systemFontOfSize:15] width:ScreenNarrowSide - 60 height:0]);
        titleHeigh = titleHeigh >= 36 ? 36 : 18;
        
        CGFloat detailTitleHeigh = ceilf([NSString sizeWithString:model.content font:[UIFont systemFontOfSize:14] width:ScreenNarrowSide - 60 height:0]);
        detailTitleHeigh = model.isOpen ? detailTitleHeigh : (detailTitleHeigh >= 34 ? 34 : 17);
        
        model.detailLabelHeight = detailTitleHeigh;
        model.cellHeight     =  16+titleHeigh+13+detailTitleHeigh+56;
        model.rootViewHeight = 16+titleHeigh+13+detailTitleHeigh+41;
        
        [weakSelf.tableView reloadData];
    }];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([NSArray isArrayEmpty:self.dataArray]) {
        return self.view.bounds.size.height;
    }
    else {
        if (self.isOneCell) {
            return  self.oneCellModel.cellHeight;
        }
        else {
            MainNewsItemModel *model = self.dataArray[indexPath.row];
            return model.cellHeight;
        }
    }
}

#pragma mark - Lazy

- (NoDataView *)noNetWorkView
{
    if (!_noNetWorkView) {
        @weakify(self);
        _noNetWorkView = [[NoDataView alloc]initWithFrame:self.view.bounds type:(ShowType_NoNetWork) clickBlock:^{
            [self_weak_ startClearBgColorLoading];
            [self_weak_.noNetWorkView removeFromSuperview];
            self_weak_.page = 1;
            [self_weak_ headerRefresh];
        }];
    }
    return _noNetWorkView;
}

- (NoDataView *)noDataView
{
    if (!_noDataView) {
        _noDataView = [[NoDataView alloc]initWithFrame:self.view.bounds type:(ShowType_NoData) clickBlock:^{}];
    }
    return _noDataView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


@end
